<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Document Clustering Server Ajax example</title>
    <style>
      body { font-family: sans-serif; max-width: 800px; margin: 0 auto }
      button + div { border: 1px solid #e0e0e0; background-color: #f8f8f8; 
        font-family: monospace; padding: 5px; margin-top: 5px; display: none }
      button + div ul { overflow: hidden; padding-left: 0; margin-left: 0; }
      button + div li { float: left; list-style-position: inside; padding-left: 20px; }
    </style>
  </head>
  
  <body>
    <h2>Document Clustering Server Ajax examples</h2>
    <p>
      This example shows how to call Document Clustering Server directly
      from web pages using JavaScript/Ajax and <tt>GET</tt> and <tt>POST</tt>
      methods. Both examples use the <tt>JSON-P</tt> response format to
      deal with same-origin-domain restrictions. Please see the source code 
      of this page for detailed comments.
    </p>
    
    <h3><tt>GET</tt> method</h3>
    <p>
      The <tt>GET</tt> method is most convenient for clustering data coming
      from external sources, in which case the request contains the query
      rather than the actual documents.
    </p>
    <button id="get">Run GET clustering</button>
    <div></div> <!-- We'll display the results here -->
    
    <h3><tt>POST</tt> method</h3>
    <p>
      The <tt>POST</tt> method is most useful when there is a need to submit
      the actual documents for clustering. The <tt>GET</tt> method is not
      suitable here due to the content length limits.
    </p>
    <button id="post">Run POST clustering</button>
    <div></div> <!-- We'll display the results here -->
    
    <!-- The examples use jQuery, feel free to use your favourite library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    
    <script>
      $(document).ready(function() {
        //
        //
        // Calling the DCS using GET method
        //
        //
        $("#get").click(function() {
          var $button = $(this), $result = $button.next("div");
          
          // Disable the button for the duration of the query
          $button.attr("disabled", true);
          
          // Show that content is loading
          $result.text("Loading...").show(100);
          
          // Make a GET request. Here we'll search the web using the 
          // "etools"document source. We'll use the JSON-P response format
          // to avoid same-origin-domain restrictions. The downside of JSON-P
          // is that we won't be able to catch errors.
          $.ajax({
            
            // The URL at which the DCS service is running
            url: "http://localhost:8080/dcs/rest",
            
            dataType: "jsonp",
            
            // Name of the GET parameter in which jQuery should 
            // provide the JSON-P callback function name.
            jsonp: "dcs.json.callback",
            
            // Request parameters
            data: {
              "dcs.source": "etools",
              "query": "data mining",
              
              "dcs.output.format": "JSON"
            },

            // Show the results when request is complete
            success: function (data) {
              $result.empty();
              
              $("<div />").text(data.documents.length + " documents retrieved, " +
                                data.clusters.length + " clusters created:")
                          .appendTo($result);
              
              var $list = $("<ul />");
              for (var i = 0; i < data.clusters.length; i++) {
                var cluster = data.clusters[i];
                $("<li />").text(cluster.phrases[0] + " (" + cluster.size + ")" ).appendTo($list);
              }
              $list.appendTo($result);
            },
            
            complete: function() {
              $button.attr("disabled", false);
            }
          });
        });

      
        //
        //
        // Calling the DCS using POST method
        //
        //

        // In this case, we'll be passing document content directly 
        // to the DCS. Here are the documents:
        var docs = [
          { "title": "Welcome to KDD-2012: August 12-16, 2012 Beijing, China | KDD 2012",  "snippet": "Introduction. The annual ACM SIGKDD conference is the premier international forum for data mining researchers and practitioners from academia, industry, and government to share …", "url": "http://kdd2012.sigkdd.org/" },
          { "title": "Sig KDD | bringing together the data mining, data science and analytics …", "snippet": "The 18th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, KDD 2012, will take place August 12-16, 2012, in Beijing, China.", "url": "http://www.kdd.org/" },
          { "title": "UCI KDD Archive", "snippet": "An online repository of large data sets which encompasses a wide variety of data types, analysis tasks, and application areas at the University of California at Irvine.", "url": "http://kdd.ics.uci.edu/" },
          { "title": "KDD 2006 Conference Home Page", "snippet": "The Twelfth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining will continue the tradition of featured keynote speakers, paper …", "url": "http://www.kdd2006.com/" },
          { "title": "Call for Papers | KDD 2012", "snippet": "Papers submitted to KDD 2012 should be original work and substantively different from papers that have been previously published or are under review in a …", "url": "http://kdd2012.sigkdd.org/cfp.shtml" },
          { "title": "Mac OS X Server", "snippet": "Welcome to Mac OS X Server Please select from these available web services No web services are available at this time. Mail Send and receive email wherever you are.", "url": "http://www.kdd.com/" },
          { "title": "K-State Laboratory for Knowledge Discovery in Databases (KDD)", "snippet": "Kansas State University Laboratory for Knowledge Discovery in Databases (KDD) - applied machine learning and probabilistic reasoning using graphical models …", "url": "http://www.kddresearch.org/" },
          { "title": "KDD 2010: 16th ACM SIGKDD Conference on Knowledge …", "snippet": "Click here for KDD Social networking. The latest conference program schedule is available if you want to start planning your activities. The conference features plenty of …", "url": "http://www.sigkdd.org/kdd2010/" },
          { "title": "Knowledge Discovery and Data Mining - KDD2009 Conference in Paris, France", "snippet": "KDD-09 will feature keynote presentations, oral paper presentations, poster sessions, workshops, tutorials, panels, exhibits, demonstrations, and the KDD Cup …", "url": "http://www.sigkdd.org/kdd2009/" },
          { "title": "KDD - Centralna KlirinA!ko Depotna DruA3ba d.d. - Domov", "snippet": "KDD v poslovanje s fiziÄ?nimi osebami, ki so imetniki nematerializiranih vrednostnih papirjev, z letom 2012 uvaja sodobnejA!e elektronske poti. Tako jim KDD v …", "url": "http://www.kdd.si/" },
          { "title": "(KDD) Program - IARPA", "snippet": "The focus of the KDD program is to develop novel approaches that will enable the intelligence analyst to effectively derive actionable intelligence from multiple, …", "url": "http://www.iarpa.gov/solicitations_kdd.html" },
          { "title": "KDD Cup from Tencent - powered by Kaggle", "snippet": "Welcome to the KDD Cup 2012! As you know, every year the KDD Cup attracts the most brilliant minds throughout the world to converge on challenging data …", "url": "http://www.kddcup2012.org/" },
          { "title": "Knowledge Discovery and Data Mining Laboratory | Istituto di …", "snippet": "The Knowledge Discovery and Data Mining Laboratory (KDD LAB) is a joint research initiative of ISTI and the Computer Science Department of the University of …", "url": "http://www-kdd.isti.cnr.it/" },
          { "title": "Celebrating 50 Glorious Years at KDD", "snippet": "KDD is a leading manufacturer and distributor of food and beverage products in the Arabian Gulf. It's the longest established, most diversified and most innovative dairy in the …", "url": "http://www.kddc.com/" },
          { "title": "Data Mining Community's Top Resource", "snippet": "Data Mining and Analytics Software, Jobs, Consulting, Courses, and more; KDnuggets News, the leading newsletter on data mining and analytics.", "url": "http://www.kdnuggets.com/" }
        ];
          
        $("#post").click(function() {
          var $button = $(this), $result = $button.next("div");
          
          // Disable the button for the duration of the query
          $button.attr("disabled", true);
          
          // Show that content is loading
          $result.text("Loading...").show(100);
          
          // Before we make the request, we need to convert the documents
          // to the XML format required by the DCS.
          var xml = "<searchresult>";
          for (var i = 0; i < docs.length; i++) {
            xml += carrot2XmlDoc(docs[i].title, docs[i].snippet, docs[i].url);
          }
          xml += "</searchresult>";
          
          // Make a POST request. Here we'll submit the documents XML we 
          // created above. We'll use the JSON-P response format
          // to avoid same-origin-domain restrictions. The downside of JSON-P
          // is that we won't be able to catch errors.
          $.support.cors = true;
          $.ajax({
            
            // The URL at which the DCS service is running
            url: "http://localhost:8080/dcs/rest",
            
            type: "post",
            
            dataType: "json",
            
            // Request parameters
            data: {
              "dcs.c2stream": xml,              
              "dcs.output.format": "JSON"
            },

            // Show the results when request is complete
            success: function (data) {
              $result.empty();
              
              $("<div />").text(data.documents.length + " documents processed, " +
                                data.clusters.length + " clusters created:")
                          .appendTo($result);
              
              var $list = $("<ul />");
              for (var i = 0; i < data.clusters.length; i++) {
                var cluster = data.clusters[i];
                $("<li />").text(cluster.phrases[0] + " (" + cluster.size + ")" ).appendTo($list);
              }
              $list.appendTo($result);
            },
            
            // Show errors            
            error: function(jqXHR, textStatus, errorThrown) {
              $result.text("Request failed. Possible causes: DCS service not available, " +
                      "cross-domain restriction.");
            },
            
            complete: function() {
              $button.attr("disabled", false);
            }
          });
          
          // Formats XML for one document in Carrot2 format
          function carrot2XmlDoc(title, snippet, url) {
            return "<document><title>" + escape(title) + "</title><snippet>" + escape(snippet) + "</snippet><url>" + escape(url) + "</url></document>";
            
            function escape(s) {
              return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
            }
          }
        });
      });
    </script>
  </body>
</html>